package tools.wordCount;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

/**
 * java实现 英文 词频统计，用于阅读源码
 */
public class WordCount {
    public static void main(String[] args) {
        String txtString = WordCount.getTxtString("src/main/java/tools/wordCount/article.txt");
        Map<String, Integer> treeMap = WordCount.getCounter(txtString);
//        treeMap.forEach((key, value) -> System.out.println(key + ": " + value));

        //将Map转为 List<Map.Entry>
        List<Map.Entry<String, Integer>> list = new ArrayList<>(treeMap.entrySet());
        //按照 value 进行倒序排序
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            //倒序排序
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
//                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for (Map.Entry<String, Integer> e : list) {
            System.out.println(e.getKey() + " : " + e.getValue());
        }

    }


    /**
     * 功能：传入路径字符串，返回文本的字符串形式
     *
     * @param path 要扫描的文件内容的 文件位置
     */
    public static String getTxtString(String path) {
        StringBuilder sBuilder = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(path));
            char[] buffer = new char[512];
            int len;
            while ((len = br.read(buffer)) != -1) {
                sBuilder.append(new String(buffer, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sBuilder.toString();
    }

    /**
     * 功能：传入文本字符串，返回单词词频
     *
     * @param txtString 文本字符串
     * @return 每个单词的词频
     */
    @SuppressWarnings("all")
    public static Map<String, Integer> getCounter(String txtString) {
        Map<String, Integer> treeMap = new TreeMap<>();
        Set<String> treeSet = new TreeSet<>();
        String[] strArr = txtString.split("[\\s?',!;.\u3000]+");
        Arrays.asList(strArr).forEach(treeSet::add);
        for (String s : treeSet) {
            int counter = 0;
            for (String s1 : strArr) {
                if (s.equals(s1)) counter++;
            }
            treeMap.put(s, counter);
        }
        return treeMap;
    }
}
